﻿using UnityEngine;
using System.Collections;

public class WebCamToFacePP : MonoBehaviour {

	private string imgName = "temp.jpg";

	Texture2D tx;

	public WebCamCap mWebCamCap;

	string resultTxt=string.Empty;

	FaceStat[] facStats;

	public FacePPMgr mFaceMgr;

	// Use this for initialization
	void Start () {
		tx	=new Texture2D(mWebCamCap.CamW, mWebCamCap.CamH, TextureFormat.RGB24, false);
	}
	
	// Update is called once per frame
	void Update () {
	

		if(mFaceMgr.enablePost)
		{
			tx.SetPixels(mWebCamCap.WebCameraTex.GetPixels());
			tx.Apply();

			byte[] pngData = tx.EncodeToJPG ();
	    	StartCoroutine (mFaceMgr.PostImage (pngData));
		}

	}


//	IEnumerator PostImage (byte[] imgBytes)
//	{
//		WWWForm form = new WWWForm ();
//		form.AddField ("api_key", api_key);
//		form.AddField ("api_secret", api_secret);
//		form.AddBinaryData ("img", imgBytes, "temp.jpg", "image/jpg");
//		form.AddField ("attribute", "glass,pose,gender,age,race,smiling");
//		WWW www = new WWW (url, form);
//		yield return www;
//
//		resultTxt=www.text;
//		//Debug.Log (www.text);
//
//		//Pay attention , we need to use  "ConvertFacepassStrToClass.FacepassStringToClasses"  to filter anything outside square brackets.
//
//		if(www.text.IndexOf("[")>=0)
//		{
//			facStats= ConvertFacepassStrToClass.FacepassStringToClasses<FaceStat>(www.text);
//			if(facStats!=null)
//			{
//				if(facStats.Length>0)
//				foreach(FaceStat mFcStat in  facStats  )
//				if(mFcStat.attribute!=null)
//				{
//						Debug.Log ("FaceStat:  "+"age: "+ mFcStat.attribute.age.range.ToString()+"range:  "+  mFcStat.attribute.age.value.ToString());
//				}
//
//			}
//		}
//	}


	void OnGUI()
	{
		if(mFaceMgr.FacStats!=null)
		{
			if(mFaceMgr.FacStats.Length>0)
				foreach(FaceStat mFcStat in  mFaceMgr.FacStats  )
				if(mFcStat.attribute!=null)
				{
					GUILayout.Label("Age: "+  mFcStat.attribute.age.value );
					GUILayout.Label("Gender: "+  mFcStat.attribute.gender.value );
					GUILayout.Label("Glass: "+  mFcStat.attribute.glass.value );
					GUILayout.Label("Race: "+  mFcStat.attribute.race.value );
					GUILayout.Label("Smiling: "+  mFcStat.attribute.smiling.value );
				
				
				}

				}
			
		}



}
